package org.mystock.candlestick.service.loader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class DataProcessor implements Runnable {

	CyclicBarrier barrier = null;

	public DataProcessor(CyclicBarrier barrier) {
		this.barrier = barrier;
	}

	@Override
	public void run() {
		String text = null;
		BufferedReader reader = TickerDataLoader.newInstance().getReader();
		synchronized (reader) {
			try {
				text = reader.readLine();
				System.out.println(text);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			barrier.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
}

public class TickerDataLoader {

	private File file = new File(
			"C:/Projects/src/candlestick-1/candlestick-core/src/main/resources/test.txt");
	private static BufferedReader reader = null;

	private static TickerDataLoader loader = null;

	private TickerDataLoader() {
		init();
	}

	public void init() {
		try {
			if (reader == null)
				reader = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void destroy() {
		try {
			if (reader != null) {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public BufferedReader getReader() {
		return reader;
	}

	public static TickerDataLoader newInstance() {
		if (loader == null) {
			loader = new TickerDataLoader();
		}
		return loader;
	}

	public static void main(String args[]) {
		int numofthreads = 10;
		CyclicBarrier barrier = new CyclicBarrier(numofthreads, new Runnable() {
			@Override
			public void run() {
				TickerDataLoader.newInstance().destroy();
			}
		});
		TickerDataLoader.newInstance().init();
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < numofthreads; i++)
			exec.execute(new DataProcessor(barrier));

		exec.shutdown();
	}

}
